'Data collection.'
import cPickle
import renderer

nodes = {}

CACHE_FILE = 'accumulator.cache'

try:
    nodes = cPickle.load(open(CACHE_FILE, 'rb'))
except:
    # file probably doesn't exist - that's absolutely fine
    pass


def add(hostname, stats, upstat):
    'Update node data accumulator.'
    # update with newer information
    if hostname in nodes:
        for key in stats:
            nodes[hostname][key] = stats[key]
    else:
        nodes[hostname] = stats
    nodes[hostname]['up']='up'

    # incorporate info about down nodes/missing monitord installs
    for hostname in upstat:
        if hostname in nodes:
            nodes[hostname]['up'] = upstat[hostname]
        else:
            nodes[hostname] = {'up':upstat[hostname]}

    # render
    renderer.render(nodes)
    
    # save data in case server goes down
    cPickle.dump(nodes, open(CACHE_FILE, 'wb'))

